// pages/search/index.js
import { request } from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";

/**
 *  防抖：运用在输入框中，防止不停输入产生请求
 *  节流：运用在多次执行中，如页面上下拉动，多次支付
 */ 

Page({
  data: {
    goods: []
  },
  // 防抖定时器
  TimeId: -1,
  // 按钮隐藏
  isFocus: false,
  inputValue: '',

  handleInput(e) {
    const { value } = e.detail
    if(!value.trim()) {
      //值不合法
      this.setData({ 
        goods: [],
        isFocus: false
      })
      clearTimeout(this.TimeId)
      return
    }
    this.setData({ isFocus: true })
    clearTimeout(this.TimeId)
    this.TimeId = setTimeout(() => {
      this.qsearch(value)
    }, 1000)
  },
  async qsearch(query) {
    const goods = await request({ url: '/goods/qsearch', data: { query } })
    this.setData({ goods })
  },
  handleCancel() {
    this.setData({  
      inputValue: '',
      isFocus: false,
      goods: []
    })
  }
})